'use strict';

angular.module('metalabPartnerApp').controller('TalentListCtrl', ['$rootScope', '$scope', '$stateParams', 'MetaResources', '$state', '$location', '$anchorScroll', 'MetaSEO', 'MetaRemind',
    'MetaUtils', 'MetaConstants',
    function ($rootScope, $scope, $stateParams, MetaResources, $state, $location, $anchorScroll, MetaSEO, MetaRemind, MetaUtils, MetaConstants) {
        $scope.myInterval = MetaConstants.slideTime;
        var favoriteObject;

        $scope.tabs = [
            {
                name: '所有人才',
                active: $state.is('meta.talent.list.all'),
                select: function () {
                    $scope.searchText = $scope.searchText || '';
                    $state.go('meta.talent.list.all');
                }
            }, {
                name: '我收藏的人才',
                active: $state.is('meta.talent.list.favorite'),
                select: function () {
                    $scope.searchText = '';
                    $state.go('meta.talent.list.favorite');
                }
            }
        ];


        /*
         * 1. 获取List列表
         */
        var getFavorited = function () {
            $scope.waitingPromise = MetaResources.favorite.query({
                userId: '_self',
                target_type: 'Talent',
                _range: MetaUtils.range($stateParams.page, $scope.numberPerPage),
                _sort: '-updatedAt',
                _embed: 'target,user,target.user'
            }, function (result, headers) {
                $scope.talents = result;
                console.log(result);
                for (var i = 0; i < $scope.talents.length; i++) {
                    $scope.talents[i] = angular.copy($scope.talents[i].target);
                    HasFavorited(i);
                }
                $scope.total = headers()['x-count'] ? parseInt(headers()['x-count']) : 0;
                $scope.page = $stateParams.page;
            }, function (err) {
                $scope.talents = null;
                $scope.total = 0;
                $scope.page = 1;
                MetaRemind.error('对不起', '服务器出错了，请稍后再尝试');
                console.log('error', err);
            }).$promise;
        };

        $scope.numberPerPage = 24;

        if ($state.is('meta.talent.list.all')) {
            $scope.waitingPromise = MetaResources.talent.query({
                _range: MetaUtils.range($stateParams.page, $scope.numberPerPage),
                _embed: 'user',
                online: true,
                _sort: '-pageViews,-updatedAt'
            }, function (result, headers) {
                $scope.talents = result;
                for (var i = 0; i < $scope.talents.length; i++) {
                    HasFavorited(i);
                }
                $scope.total = headers()['x-count'] ? parseInt(headers()['x-count']) : 0;
                $scope.page = $stateParams.page;
            }, function (error) {
                MetaRemind.error(error);
            }).$promise;
        } else if ($state.is('meta.talent.list.favorite')) {
            getFavorited();
        }


        /**
         * @function 是否已收藏
         */
        var HasFavorited = function (i) {
            // if ($state.is('meta.talent.list.favorite')) {
            //     item.isFavorited = true;
            // }
            console.log(i);
            var favoritePromise = MetaResources.favorite.exist({
                'userId': '_self',
                'targetId': $scope.talents[i].id
            }, function (data) {
                $scope.talents[i].isFavorited = true;
                $scope.talents[i].favoriteObject = data;
            }, function () {
                $scope.talents[i].isFavorited = false;
            }).$promise;

            return favoritePromise;
        };

        /**
         * @function 收藏
         */
        $scope.Favorite = function (item) {
            if (item.isFavorited) {
                MetaResources.favorite.delete({
                    'id': item.favoriteObject.id
                }, function () {
                    item.isFavorited = false;
                    MetaRemind.success('您已经取消收藏该人才');
                    if ($state.is('meta.talent.list.favorite')) {
                        getFavorited();
                    }
                }, function () {
                    MetaRemind.error('对不起，取消收藏失败，请稍后再试');
                });
            } else {
                MetaResources.favorite.add({
                    userId: '_self',
                    'targetId': item.id,
                    'targetType': 'Talent'
                }, null, function (success) {
                    item.isFavorited = true;
                    item.favoriteObject = success;
                    MetaRemind.success("收藏成功！");
                }, function (err) {
                    item.isFavorited = false;
                    MetaRemind.error("对不起，收藏失败！请稍后再试……");
                });
            }
        }

        /**
         * 开通人才
         * @author Yud
         */
        $scope.openTalent = function () {
            MetaResources.talent.open({'userId': '_self'}, {}, function (data) {
                MetaRemind.success('开通成功');
                $rootScope.USER.talentOpened = true;
                $state.go('meta.talent.edit');
            }, function (error) {
                MetaRemind.error(error);
            });
        };

        $scope.search = function (form) {
            form.searchText.$viewValue ? $state.go('meta.talent.search', {keywords: form.searchText.$viewValue}) : MetaRemind.warn('请输入关键字进行搜索！');
        };

        $scope.goSearch = function (form) {
            form.keywords.$viewValue ? $state.go('meta.talent.search', {keywords: form.keywords.$viewValue}) : MetaRemind.warn('请输入关键字进行搜索！');
        };

        MetaSEO.setSEO("迈科技-科技人才与产业技术搜索引擎","迈科技-科技人才与产业技术搜索引擎","迈科技,科技人才与产业技术搜索引擎,技术搜索引擎，搜索引擎，科技人才搜索，技术搜索");
    }]);
